<template>
  <div class="property-history">
    <el-card class="mb-4">
      <el-form :inline="true" :model="queryForm" class="flex items-center flex-wrap gap-4" label-width="60px">
        <div class="flex flex-wrap items-center gap-4">
          <el-form-item label="设备" class="mb-0" style="margin-right: 10px;">
            <el-select 
              v-model="queryForm.deviceId" 
              filterable
              placeholder="请选择设备"
              style="width: 300px"
              @change="handleDeviceChange"
              clearable
            >
              <el-option
                v-for="item in deviceOptions"
                :key="item.id"
                :label="`${item.name}(${item.id})`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间" class="mb-0" style="margin-right: 10px;">
            <el-date-picker
              v-model="queryForm.timeRange"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              @change="handleTimeChange"
              style="width: 380px"
            />
          </el-form-item>
          
          <el-form-item class="mb-0" style="margin-right: 10px;">
            <el-button type="primary" :loading="loading" @click="fetchPropertyHistory" :disabled="!queryForm.deviceId">
              查询
            </el-button>
            <el-button type="success" :disabled="!queryForm.deviceId" @click="exportDeviceData">
              导出设备数据
            </el-button>
            <el-button type="success" :disabled="!queryForm.deviceId || !activePropertyTab" @click="exportToExcel">
              导出当前数据
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
    
    <el-card v-if="selectedDevice">
      <template #header>
        <div class="flex justify-between items-center">
          <span>设备: {{ selectedDevice.name }} ({{ selectedDevice.id }})</span>
        </div>
      </template>
      
      <el-tabs v-model="activePropertyTab" type="card" @tab-change="handlePropertyTabChange">
        <el-tab-pane 
          v-for="property in propertyList" 
          :key="property.identifier"
          :label="`${property.name}(${property.identifier})`"
          :name="property.identifier"
        >
          <div class="chart-container">
            <PropertyChart 
              v-show="property.identifier === activePropertyTab"
              :name="property.name" 
              :properties="propertyHistoryData[property.identifier] || []" 
              :key="`${queryForm.deviceId}-${property.identifier}`"
            />
          </div>
          
          <el-table 
            :data="propertyHistoryData[property.identifier] || []" 
            border 
            style="width: 100%" 
            class="mt-4"
            v-loading="loading"
            ref="tableRef"
          >
            <el-table-column prop="time" label="时间" width="200">
              <template #default="scope">
                {{ formatDate(scope.row.time) }}
              </template>
            </el-table-column>
            <el-table-column prop="value" :label="`${property.name}(${property.identifier})`">
              <template #default="scope">
                {{ formatValue(scope.row.value) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <el-empty v-if="!selectedDevice && !loading" description="请选择设备进行查询" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { DeviceInfoApi } from '@/api/eiot/deviceinfo'
import { devicePropertyLogs } from '@/api/eiot/deviceinfo/devices.api'
import PropertyChart from './modules/PropertyChart.vue'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'

const route = useRoute()
const router = useRouter()
const tableRef = ref()

// 查询表单
const queryForm = reactive({
  deviceId: '',
  timeRange: [
    new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 默认一周前
    new Date() // 当前时间
  ]
})

// 设备相关
const deviceOptions = ref<any[]>([])
const selectedDevice = ref<any>(null)

// 属性相关
const propertyList = ref<any[]>([])
const propertyHistoryData = ref<any>({})
const activePropertyTab = ref('')

// 其他状态
const loading = ref(false)

// 时间选择器选项
const pickerOptions = {
  shortcuts: [
    {
      text: '最近1小时',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近6小时',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 6)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近1天',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近3天',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
        picker.$emit('pick', [start, end])
      }
    },
    {
      text: '最近1周',
      onClick(picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        picker.$emit('pick', [start, end])
      }
    }
  ]
}

// 获取所有设备
const getAllDevices = async () => {
  try {
    const res = await DeviceInfoApi.getDeviceInfoPage({
      pageNo: 1,
      pageSize: 100 // 每页最大显示100个设备
    })
    deviceOptions.value = res.list || []
  } catch (err) {
    console.error('获取设备列表失败:', err)
    // 添加更详细的错误信息
    if (err instanceof SyntaxError) {
      console.error('JSON解析错误，API可能返回了非JSON格式的数据')
    }
  }
}

// 设备变更处理
const handleDeviceChange = async (deviceId) => {
  if (!deviceId) {
    selectedDevice.value = null
    propertyList.value = []
    propertyHistoryData.value = {}
    return
  }
  
  loading.value = true
  try {
    // 获取设备详情
    const deviceDetail = await DeviceInfoApi.getDeviceInfo(deviceId)
    selectedDevice.value = deviceDetail
    
    // 获取设备属性列表
    const deviceWithProperty = await DeviceInfoApi.getDeviceProperties(deviceId)
    const propertyMap = deviceWithProperty.identifier2property || {}
    
    // 构建属性列表
    const properties = Object.keys(propertyMap).map(key => ({
      identifier: key,
      name: propertyMap[key].name || key,
      value: propertyMap[key].value
    }))
    
    propertyList.value = properties
    
    // 默认选中第一个属性
    if (properties.length > 0) {
      activePropertyTab.value = properties[0].identifier
      await fetchPropertyHistory()
    }
  } catch (err) {
    console.error('获取设备信息失败:', err)
  } finally {
    loading.value = false
  }
}

// 时间变更处理
const handleTimeChange = () => {
  if (queryForm.deviceId && activePropertyTab.value) {
    fetchPropertyHistory()
  }
}

// 获取属性历史数据
const fetchPropertyHistory = async () => {
  if (!queryForm.deviceId || !activePropertyTab.value) return
  
  loading.value = true
  try {
    const data = await devicePropertyLogs({
      deviceId: queryForm.deviceId,
      name: activePropertyTab.value,
      start: queryForm.timeRange[0].getTime(),
      end: queryForm.timeRange[1].getTime()
    })
    
    // 更新对应属性的历史数据
    propertyHistoryData.value[activePropertyTab.value] = data || []
  } catch (err) {
    console.error('获取属性历史数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 属性标签页变更处理
const handlePropertyTabChange = (tabName) => {
  activePropertyTab.value = tabName
  // 如果该属性还没有历史数据，则获取
  if (!propertyHistoryData.value[tabName]) {
    fetchPropertyHistory()
  }
}

// 格式化显示值，处理特殊字符显示问题
const formatValue = (value) => {
  // 处理可能存在的特殊字符，如韩文"값"等显示异常问题
  if (typeof value === 'string') {
    // 尝试解码可能的编码问题
    try {
      // 如果是包含特殊编码的字符串，尝试解码
      return decodeURIComponent(escape(value))
    } catch (e) {
      // 解码失败时，直接返回原值
      return value
    }
  }
  return value
}

// 导出设备数据
const exportDeviceData = async () => {
  if (!queryForm.deviceId) return
  
  try {
    loading.value = true
    // 获取所有属性的历史数据
    const exportData = {}
    for (const property of propertyList.value) {
      const data = await devicePropertyLogs({
        deviceId: queryForm.deviceId,
        name: property.identifier,
        start: queryForm.timeRange[0].getTime(),
        end: queryForm.timeRange[1].getTime()
      })
      exportData[property.identifier] = data || []
    }
    
    // 准备导出内容
    let csvContent = '\uFEFF设备ID,设备名称,属性标识,属性名称,时间,값\n'
    
    propertyList.value.forEach(property => {
      const data = exportData[property.identifier] || []
      data.forEach(item => {
        // 对值进行特殊处理，确保韩文能正确显示
        const processedValue = typeof item.value === 'string' ? 
          decodeURIComponent(escape(item.value)) : 
          item.value;
          
        csvContent += `${queryForm.deviceId},${selectedDevice.value.name},${property.identifier},${property.name},${formatDate(item.time)},${processedValue}\n`
      })
    })
    
    // 创建并下载文件
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const fileName = `${selectedDevice.value.name}_设备数据_${formatDate(new Date())}.csv`
    download.excel(blob, fileName)
  } catch (err) {
    console.error('导出设备数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 导出为Excel
const exportToExcel = () => {
  if (!queryForm.deviceId || !activePropertyTab.value) return
  
  const property = propertyList.value.find(p => p.identifier === activePropertyTab.value)
  if (!property) return
  
  const data = propertyHistoryData.value[activePropertyTab.value] || []
  if (data.length === 0) {
    // 如果没有数据，提示用户
    alert('当前属性没有历史数据可导出')
    return
  }
  
  // 准备导出数据
  let csvContent = `\uFEFF时间,${property.name}값\n` // 添加BOM以支持中文
  
  data.forEach(item => {
    csvContent += `${formatDate(item.time)},${item.value}\n`
  })
  
  // 导出文件
  const blob = new Blob(['\uFEFF' + csvContent], { 
    type: 'text/csv;charset=utf-8;' 
  })
  
  const fileName = `${selectedDevice.value.name}_${property.name}_历史数据_${formatDate(new Date())}.csv`
  download.excel(blob, fileName)
}

// 组件挂载时初始化
onMounted(async () => {
  await getAllDevices()
  
  // 如果URL中有deviceId参数，则自动选择该设备
  const deviceId = route.query.deviceId
  if (deviceId) {
    queryForm.deviceId = deviceId
    handleDeviceChange(deviceId)
  } else if (deviceOptions.value.length > 0) {
    // 默认选择第一个设备
    queryForm.deviceId = deviceOptions.value[0].id
    handleDeviceChange(deviceOptions.value[0].id)
  }
})
</script>

<style scoped lang="scss">
.property-history {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 120px);
}

.chart-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}
</style>
